/*
 *   Copyright 2021 zzh
 *
 *   Licensed under the Apache License, Version 2.0 (the "License");
 *   you may not use this file except in compliance with the License.
 *   You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *   Unless required by applicable law or agreed to in writing, software
 *   distributed under the License is distributed on an "AS IS" BASIS,
 *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *   See the License for the specific language governing permissions and
 *   limitations under the License.
 *
 */

package com.aduib.boot.web.context.async;

import com.aduib.boot.common.concurrent.ThreadFactoryBuilder;
import com.aduib.boot.web.constants.AppConstants;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.ThreadPoolExecutor;

/**
 * @description: ScheduleAutoConfiguration
 * @author: zzh
 * @date: 2021/9/13 14:39
 */
@ConditionalOnProperty(prefix= AppConstants.PROPERTY_PREFIX,name="enabledAsync",havingValue = "true")
@EnableAsync
public class AsyncAutoConfiguration {

  @Bean("AsyncTaskExecutor") // bean的名称，默认为首字母小写的方法名
  public ThreadPoolTaskExecutor getAsyncExecutor(){
    ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
    executor.setCorePoolSize(10);
    executor.setMaxPoolSize(50);
    executor.setQueueCapacity(100);
    executor.setKeepAliveSeconds(10);
    executor.setThreadFactory(ThreadFactoryBuilder.createJava("aduib-web-async",Thread.NORM_PRIORITY,false));

    // 线程池对拒绝任务的处理策略
    executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
    // 初始化
    executor.initialize();
    return executor;
  }
}
